import { StyleSheet, Text, View, ScrollView, Image, Pressable, Modal } from 'react-native';
import React, { useState, useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Picker } from 'react-native-wheel-pick';
import { NavBarHeader } from '~/components';
import { deviceStore, observer } from '~/store';
import { getRealTimeWifi, setRealTimeWifi, getTimeUpload, setTimeUpload } from '~/utils/ble/application';
import { px2dp, scale, width } from '~/utils/px2dp';

const morningData = [0, 1, 2, 3, 4, 5, 6, 7];
const noonData = [8, 9, 10, 11, 12, 13, 14, 15];
const nightData = [16, 17, 18, 19, 20, 21, 22, 23];

export default observer(() => {
    const { t } = useTranslation();
    const { wifiRealUploadStatus, wifiTimingData } = deviceStore;
    const [data, setData] = useState<any>(wifiTimingData); // 开始默认数据
    const [timeData, setTimeData] = useState<any>([data[1], data[5], data[9]]);
    const [upsats, setUpsats] = useState(data[0]); //获取总开关

    const [type, setType] = useState<any>('morning'); //获取早中晚类型
    const getRealTime = () => {
        getRealTimeWifi({ type: 'ble' });
    };
    const setRealTime = () => {
        setRealTimeWifi({ type: 'ble' }, wifiRealUploadStatus == 1 ? 0 : 1);
        setTimeout(() => {
            getRealTime();
        }, 200);
    };

    // 定时上传数据设置
    const setTimeStatus = () => {
        data[0] = upsats === 1 ? 0 : 1;
        setData(data);
        setTimeUpload({ type: 'ble' }, data);
        setUpsats(upsats === 1 ? 0 : 1);
        setTimeout(() => {
            getUploadStatus();
        }, 200);
    };
    const getUploadStatus = () => {
        getTimeUpload({ type: 'ble' });
    };
    // 编辑时间
    const [timeValue, setTimeValue] = useState(0);
    const [editVisible, setEditVisible] = useState(false);
    const [editIndex, seteditIndex] = useState(-1);
    const editTime = (index: number) => {
        setEditVisible(true);
        seteditIndex(index);
    };
    const editSwitch = (index: number) => {
        switch (index) {
            case 0:
                editSwitchCommen(4);
                break;
            case 1:
                editSwitchCommen(8);
                break;
            case 2:
                editSwitchCommen(12);
                break;
            default:
                break;
        }
    };
    const pickerData = useMemo(() => {
        if (type == 'morning') {
            return morningData;
        } else if (type == 'noon') {
            return noonData;
        } else {
            return nightData;
        }
    }, [morningData, nightData, noonData, type]);
    const editSwitchCommen = (dataIndex: number) => {
        data[dataIndex] = data[dataIndex] === 1 ? 0 : 1;
        setData(data);
        setTimeUpload({ type: 'ble' }, data);
        setTimeout(() => {
            getUploadStatus();
        }, 500);
    };
    const confirm = () => {
        switch (editIndex) {
            case 0:
                editCommenTime(timeValue, 1, 2, 3, 0);
                break;
            case 1:
                editCommenTime(timeValue, 5, 6, 7, 1);
                break;
            case 2:
                editCommenTime(timeValue, 9, 10, 11, 2);
                break;
            default:
                break;
        }
        setEditVisible(false);
    };
    const editCommenTime = (result: any, dataIndex: number, minIndex: number, sIndex: number, newTimeIndex: number) => {
        const min = 0;
        const max = 1200;
        const s = Math.round(Math.random() * (max - min)) + min;
        const m = Math.round((s % 3600) / 60);
        const ss = s % 60;
        data[dataIndex] = result;
        timeData[newTimeIndex] = result;
        data[minIndex] = m;
        data[sIndex] = ss;
        setTimeData(timeData);
        setTimeUpload({ type: 'ble' }, data);
        setTimeout(() => {
            getUploadStatus();
        }, 500);
    };

    useEffect(() => {
        getRealTime();
        setTimeout(() => {
            getUploadStatus();
        }, 200);
    }, []);
    useEffect(() => {
        setData(deviceStore.wifiTimingData);
    }, [deviceStore.wifiTimingData]);
    return (
        <View style={styles.container}>
            <NavBarHeader title={t('UploadSettings.t1')} />
            <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={styles.contentStyle}>
                <View style={[styles.card, styles.row, styles.between]}>
                    <View>
                        <Text style={styles.title}>{t('UploadSettings.t2')}</Text>
                        <Text style={styles.t1} numberOfLines={2}>
                            {t('UploadSettings.t3')}
                        </Text>
                    </View>
                    <Pressable onPress={() => setRealTime()}>
                        <Image
                            style={styles.switchIcon}
                            resizeMode="contain"
                            source={
                                wifiRealUploadStatus == 1
                                    ? require('~/assets/device/open.png')
                                    : require('~/assets/device/close.png')
                            }
                        />
                    </Pressable>
                </View>

                <View style={[styles.card, styles.row, styles.between]}>
                    <View>
                        <Text style={styles.title}>{t('UploadSettings.t4')}</Text>
                        <Text style={styles.t1} numberOfLines={2}>
                            {t('UploadSettings.t5')}
                        </Text>
                    </View>
                    <Pressable onPress={setTimeStatus}>
                        <Image
                            style={styles.switchIcon}
                            resizeMode="contain"
                            source={
                                data[0] == 1
                                    ? require('~/assets/device/open.png')
                                    : require('~/assets/device/close.png')
                            }
                        />
                    </Pressable>
                </View>
                <View style={[styles.card]}>
                    <Text style={styles.title}>{t('UploadSettings.t6')}</Text>
                    {/*  */}
                    <View style={styles.listItem}>
                        <View style={[styles.row, styles.between]}>
                            <Pressable
                                style={styles.row}
                                onPress={() => {
                                    setType('morning');
                                    editTime(0);
                                }}>
                                <Text style={styles.title}>{data[1].toString().padStart(2, '0') + ':00'}</Text>
                                <Text style={styles.t2}>{t('UploadSettings.t7')}</Text>
                            </Pressable>
                            <Pressable onPress={() => editSwitch(0)}>
                                <Image
                                    style={styles.switchIcon}
                                    resizeMode="contain"
                                    source={
                                        data[4] == 1
                                            ? require('~/assets/device/open.png')
                                            : require('~/assets/device/close.png')
                                    }
                                />
                            </Pressable>
                        </View>
                    </View>
                    {/*  */}
                    <View style={styles.listItem}>
                        <View style={[styles.row, styles.between]}>
                            <Pressable
                                style={styles.row}
                                onPress={() => {
                                    setType('noon');
                                    editTime(1);
                                }}>
                                <Text style={styles.title}>{data[5]?.toString()?.padStart(2, '0') + ':00'}</Text>
                                <Text style={styles.t2}>{t('UploadSettings.t7')}</Text>
                            </Pressable>
                            <Pressable onPress={() => editSwitch(1)}>
                                <Image
                                    style={styles.switchIcon}
                                    resizeMode="contain"
                                    source={
                                        data[8] == 1
                                            ? require('~/assets/device/open.png')
                                            : require('~/assets/device/close.png')
                                    }
                                />
                            </Pressable>
                        </View>
                    </View>
                    {/*  */}
                    <View style={[styles.listItem, { borderBottomColor: '#fff' }]}>
                        <View style={[styles.row, styles.between]}>
                            <Pressable
                                style={styles.row}
                                onPress={() => {
                                    setType('night');
                                    editTime(2);
                                }}>
                                <Text style={styles.title}>{data[9]?.toString()?.padStart(2, '0') + ':00'}</Text>
                                <Text style={styles.t2}>{t('UploadSettings.t7')}</Text>
                            </Pressable>
                            <Pressable onPress={() => editSwitch(2)}>
                                <Image
                                    style={styles.switchIcon}
                                    resizeMode="contain"
                                    source={
                                        data[12] == 1
                                            ? require('~/assets/device/open.png')
                                            : require('~/assets/device/close.png')
                                    }
                                />
                            </Pressable>
                        </View>
                    </View>
                </View>
            </ScrollView>
            <Modal
                visible={editVisible}
                animationType="fade"
                transparent={true}
                statusBarTranslucent={true}
                hardwareAccelerated={true}
                onRequestClose={() => setEditVisible(false)}>
                <View style={styles.modalContainer}>
                    <View style={styles.modal}>
                        <View style={[styles.row, styles.between]}>
                            <Pressable onPress={() => setEditVisible(false)}>
                                <Text style={styles.cancleText}>{t('UploadSettings.t8')}</Text>
                            </Pressable>
                            <Text style={styles.title}>{t('UploadSettings.t9')}</Text>
                            <Pressable onPress={() => confirm()}>
                                <Text style={styles.confirmText}>{t('UploadSettings.t10')}</Text>
                            </Pressable>
                        </View>
                        <View style={styles.pickerCard}>
                            <Picker
                                style={styles.pciker}
                                itemStyle={styles.itemStyle}
                                textSize={32}
                                pickerData={pickerData}
                                onValueChange={(index) => {
                                    setTimeValue(index);
                                }}
                            />
                        </View>
                    </View>
                </View>
            </Modal>
        </View>
    );
});

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    between: {
        justifyContent: 'space-between',
    },
    container: {
        flex: 1,
    },
    contentStyle: {
        flexGrow: 1,
        paddingBottom: '20%',
    },
    card: {
        backgroundColor: '#fff',
        borderRadius: px2dp(24),
        marginHorizontal: px2dp(24),
        marginTop: px2dp(24),
        padding: px2dp(24),
    },
    title: {
        color: '#000',
        fontSize: scale(32),
        fontWeight: 'bold',
    },
    t1: {
        color: '#a4a4a4',
        fontSize: scale(26),
        marginTop: px2dp(12),
        width: px2dp(500),
        lineHeight: px2dp(40),
    },
    switchIcon: {
        width: px2dp(120),
        height: px2dp(50),
    },
    t2: {
        color: '#a4a4a4',
        fontSize: scale(26),
        marginLeft: px2dp(24),
    },
    listItem: {
        marginTop: px2dp(32),
        height: px2dp(120),
        borderBottomWidth: 1,
        borderColor: '#eee',
        justifyContent: 'center',
    },
    modalContainer: {
        flex: 1,
        backgroundColor: 'rgba(0,0,0,0.6)',
        justifyContent: 'flex-end',
    },
    modal: {
        backgroundColor: '#fff',
        borderTopLeftRadius: 12,
        borderTopRightRadius: 12,
        padding: 14,
        height: '50%',
    },
    cancleText: {
        color: '#a4a4a4',
        fontSize: scale(28),
        fontWeight: 'bold',
    },
    confirmText: {
        color: '#000',
        fontSize: scale(28),
        fontWeight: 'bold',
    },
    pickerCard: {
        flexDirection: 'row',
        alignItems: 'center',
        alignSelf: 'center',
    },
    pciker: {
        marginTop: px2dp(32),
        height: px2dp(600),
        width: width,
        backgroundColor: '#fff',
    },
    itemStyle: {
        color: '#191919',
        fontWeight: 'bold',
        height: px2dp(600),
    },
});
